package com.fang.algorithm.leecode;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description 反转链表
 * 给你单链表的头节点 head ，请你反转链表，并返回反转后的链表
 * 输入：head = [1,2,3,4,5]
 * 输出：[5,4,3,2,1]
 * @date 2022/1/17 10:29 下午
 **/
public class Test05_ReverseLinkList {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        print(node1);
        ListNode reverseList = reverseList(node1);
        print(reverseList);
    }

    private static ListNode reverseList(ListNode head) {
        if (null == head || null == head.next){
            return head;
        }
        ListNode perv = null;
        ListNode curr = head;
        while (null != curr){
            ListNode tempNode = curr.next;
            curr.next = perv;
            perv = curr;
            curr = tempNode;
        }
        return perv;
    }

    private static void print(ListNode node) {
        if (node == null) {
            return;
        }
        while (node.next != null){
            System.out.print(node.val + "->");
            node = node.next;
        }
        System.out.println(node.val);
    }
}